package com.mxp.influx.client.utils;

import org.influxdb.dto.QueryResult;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 公共工具类
 * @author maoxp
 * @date 2024-12-24 16:40
 */
public class PublicUtil {
    /**
     * 获取数据
     * @param query
     * @param keys
     * @return
     */
    public static List<Map<String, Object>> getInfluxDBMapList(QueryResult query, LinkedHashSet<String> keys) {
        query = query == null ? new QueryResult() : query;
        QueryResult.Result result = query.getResults().get(0);
        result = result == null ? new QueryResult.Result() : result;
        List<QueryResult.Series> resultSeries = result.getSeries() == null ? new ArrayList<>() : result.getSeries();
        QueryResult.Series series = CollectionUtils.isEmpty(resultSeries) ? new QueryResult.Series() : resultSeries.get(0);
        List<List<Object>> value = series.getValues() == null ? new ArrayList<>() : series.getValues();
        List<String> key = series.getColumns() == null ? new ArrayList<>() : series.getColumns();

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        for (List<Object> objects : value) {
            map = new HashMap<>();
            for (int j = 0; j < objects.size(); j++) {
                Object valueStr = objects.get(j) == null ? null : String.valueOf(objects.get(j));
                map.put(key.get(j), valueStr);
                if (keys != null) {
                    keys.add(key.get(j));
                }
            }
            list.add(map);
        }
        return list;
    }

    /**
     * 获取数据
     * @param query
     * @return
     */
    public static List<Map<String, Object>> getInfluxDBMapList(QueryResult query) {
        return getInfluxDBMapList(query, null);
    }

    /**
     * 获取表格数据
     * @param query
     * @return
     */
    public static Map<String, Object> getInfluxDBTableObj(QueryResult query) {
        LinkedHashSet<String> columns = new LinkedHashSet<>();
        List<Map<String, Object>> data = getInfluxDBMapList(query, columns);
        HashMap<String, Object> result = new HashMap<>();
        result.put("columns", columns);
        result.put("data", data);
        return result;
    }

    /**
     * 创建文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static void createFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        Path directoryPath = path.getParent();
        if (!Files.exists(directoryPath)) {
            Files.createDirectories(directoryPath);
        }
        File file = path.toFile();
        if (!file.exists()) {
            file.createNewFile();
        }
    }
}
